from django.db.models import Count
from django.shortcuts import render
from django.utils import timezone

from apps.app_focus.models import Focus
from apps.app_post.models import Post, Category
from apps.app_talk.models import Mood, Talk
from utils.frontContext import front_context


def index(request):
    context = front_context()
    focuses = Focus.objects.filter(end_time__gt=timezone.now()).order_by('priority')
    context['focuses'] = focuses
    return render(request, 'front/index.html', context=context)


def detail_view(request, pid):
    try:
        post = Post.objects.select_related('author', 'category').get(pk=pid)
        context = front_context()
        context['post'] = post
    except Post.DoesNotExist:
        return render(request, 'error.html', {'msg': '该文章不存在'})
    return render(request, 'front/detail.html', context=context)


def category_view(request):
    categories = Category.objects.annotate(post_num=Count('posts')).order_by('-post_num')
    context = front_context()
    context['categories'] = categories
    return render(request, 'front/category.html', context=context)


def mood_view(request):
    moods = Mood.objects.annotate(post_num=Count('talks')).order_by('-post_num')
    context = front_context()
    context['moods'] = moods
    return render(request, 'front/mood.html', context=context)


def talk_view(request, id):
    try:
        talk = Talk.objects.select_related('mood').get(id=id)
        context = front_context()
        context['talk'] = talk
    except Post.DoesNotExist:
        return render(request, 'error.html', {'msg': '该文章不存在'})
    return render(request, 'front/talk.html', context=context)


def search_view(request):
    context = front_context()
    focuses = Focus.objects.filter(end_time__gt=timezone.now()).order_by('priority')
    context['focuses'] = focuses
    return render(request, 'front/search.html', context=context)
